/*
 * Copyright (c) 2010 All Inclusive Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.framework.web.ajax.convertor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.googlecode.framework.core.json.JsonMapper;
import com.googlecode.framework.web.ajax.AjaxHandleException;

/**
 * <p>
 * 将业务层获取的数据转换成JSON形式的字符串
 * </p>
 * 
 * @author xiayg
 *
 */
public class JsonConvertor implements ResponseConvertor {

    /**
     * Logger
     */
    private Logger logger = LoggerFactory.getLogger(getClass());
    
    /**
     * Response中的编码
     */
    public static final String ENCODING = "UTF-8";
    
    /**
     * JsonMapper
     */
    private JsonMapper jsonMapper;
    
    public JsonConvertor(JsonMapper jsonMapper) {
        this.jsonMapper = jsonMapper;
    }
    
    /**
     * 将业务层获取的数据转换成JSON形式的字符串输出到Response中
     * @param obj
     * @param request　
     * @param response
     */
	public void convert(Object obj, HttpServletRequest request, HttpServletResponse response) {
	    // JSON形式的字符串
        String output = jsonMapper.toJson(obj);
        if (logger.isDebugEnabled()) {
            logger.debug("JSON: " + output);
        }
        
		PrintWriter writer;
		try {
			response.setContentType("text/html; charset=" + ENCODING);
			response.addHeader("Content-Type", "text/html");
			response.addHeader("charset", ENCODING);
			response.addHeader("Cache-Control", "no-cache");
			response.addHeader("Pragma", "no-cache");
			response.addHeader("Expires", "0");

			writer = response.getWriter();
			writer.print(output);
			//writer.close();
		} catch (IOException e) {
			throw new AjaxHandleException(e);
		}
	}

}
